package loader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.Format;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

public class XMLHandler {

	private Loader loader;

	public XMLHandler(Loader loader) {
		this.loader = loader;
	}

	private String getLocalName() {
		String clientName = "Unbekannt";
		InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		if (addr != null)
			clientName = addr.getHostName();
		if (clientName.endsWith("-PC"))
			clientName = clientName.substring(0, clientName.length() - 3);
		return clientName;
	}

	public void convertFromUpdateXML() {
		try {

			// Create instance of DocumentBuilderFactory
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();

			// Get the DocumentBuilder
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			URL xmlurl = new URL(
					"http://www.galerie-peterschultz.de/content/update.xml");
			InputStream stream = xmlurl.openStream();
			Document doc = docBuilder.parse(stream);

			// create the root element
			Element root = doc.getDocumentElement();

			NodeList itemList = root.getElementsByTagName("update");
			for (int i = 0; i < itemList.getLength(); i++) {
				Element currentBook = (Element) itemList.item(i);

				String version = currentBook.getElementsByTagName("version")
						.item(0).getTextContent().trim();
				String updatetext = currentBook
						.getElementsByTagName("description").item(0)
						.getTextContent().trim();
				String updatetext2 = currentBook
						.getElementsByTagName("description2").item(0)
						.getTextContent().trim();
				String url = currentBook.getElementsByTagName("url").item(0)
						.getTextContent().trim();
				loader.push(version, updatetext, updatetext2, url);
			}
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	public void convertFromUpdateXMLLocal() {
		try {
			File file = new File(loader.getLocalPath() + "update.xml");
			if(!file.isFile()) {
				loader.pushLocal("100");
				return;
			}
			// Create instance of DocumentBuilderFactory
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();

			// Get the DocumentBuilder
			DocumentBuilder docBuilder = factory.newDocumentBuilder();

			// Using existing XML Document
			Document doc = docBuilder.parse(file);

			// create the root element
			Element root = doc.getDocumentElement();

			NodeList bookList = root.getElementsByTagName("update");
			System.out.println(bookList.getLength());
			for (int i = 0; i < bookList.getLength(); i++) {
				System.out.println(i);
				Element currentBook = (Element) bookList.item(i);

				String version = currentBook.getElementsByTagName("version")
						.item(0).getTextContent().trim();

				loader.pushLocal(version);
			}
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	public void saveNewVersionLocal() {
		try {

			// Create instance of DocumentBuilderFactory
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();

			// Get the DocumentBuilder
			DocumentBuilder docBuilder = factory.newDocumentBuilder();

			Document doc = docBuilder.newDocument();
			Node mainNode = doc.createElement("update");

			// *************************************************

			Node childNode;
			Node aNode;

			Text aTextNode;

			childNode = doc.createElement("update");
			aNode = doc.createElement("version");

			aTextNode = doc.createTextNode("" + loader.getNewVersion());

			aNode.appendChild(aTextNode);

			childNode.appendChild(aNode);

			mainNode.appendChild(childNode);

			doc.appendChild(mainNode);
			doc.normalize();
			Transformer transformer = TransformerFactory.newInstance()
					.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(
					"{http://xml.apache.org/xslt}indent-amount", "2");
			DOMSource source = new DOMSource(doc);

			FileOutputStream os = new FileOutputStream(new File(
					loader.getLocalPath() + "update.xml"));
			StreamResult result = new StreamResult(os);
			transformer.transform(source, result);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

	public void convertXMLLog(String titel, String logentry) {

		try {

			// Create instance of DocumentBuilderFactory
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();

			// Get the DocumentBuilder
			DocumentBuilder docBuilder = factory.newDocumentBuilder();

			// Using existing XML Document
			// Document doc = docBuilder.parse(file);

			// tsuji:note [b] change this
			// Document doc = docBuilder.parse (new File("book.xml"));
			URL xmlurl = new URL(
					"http://www.galerie-peterschultz.de/content/log.xml");
			InputStream stream = xmlurl.openStream();
			Document doc = docBuilder.parse(stream);

			// create the root element
			Element root = doc.getDocumentElement();

			Node childNode = doc.createElement("log");
			Node aNode;
			Node bNode;
			Node cNode;

			Text aTextNode;
			Text bTextNode;
			Text cTextNode;

			aNode = doc.createElement("datum");
			bNode = doc.createElement("titel");
			cNode = doc.createElement("logeintrag");

			aTextNode = doc.createTextNode(getDate()+", "+getLocalName());
			bTextNode = doc.createTextNode(titel);
			cTextNode = doc.createTextNode(logentry);

			aNode.appendChild(aTextNode);
			bNode.appendChild(bTextNode);
			cNode.appendChild(cTextNode);

			childNode.appendChild(aNode);
			childNode.appendChild(bNode);
			childNode.appendChild(cNode);

			root.appendChild(childNode);

			doc.normalize();
			Transformer transformer = TransformerFactory.newInstance()
					.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(
					"{http://xml.apache.org/xslt}indent-amount", "2");
			DOMSource source = new DOMSource(doc);

			FileOutputStream os = new FileOutputStream(new File(
					"c:/temp/FTP/content/log.xml"));
			StreamResult result = new StreamResult(os);
			transformer.transform(source, result);

		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

	public String getDate() {
		Calendar calendar = new GregorianCalendar();
		Format format = DateFormat.getDateTimeInstance(DateFormat.SHORT,
				DateFormat.SHORT);
		Date date = calendar.getTime();
		return format.format(date);
	}

}